package com.matrix.draft.juc.day2;

import lombok.SneakyThrows;

import java.util.concurrent.*;

public class Main {

    private static ExecutorService executor = Executors.newFixedThreadPool(2);

    public static void t1() {

        CompletableFuture<Object> future = CompletableFuture.<Object>supplyAsync(() -> {
//            threadSleep(5000);
            return 123;
        }, executor).applyToEitherAsync(CompletableFuture.<Object>supplyAsync(() -> {
            threadSleep(3000);
            return new TimeoutException();
        }), r -> {
            return r instanceof Exception ? null : r;
        }, executor);

        System.out.println(future.join());

    }

    public static void threadSleep(int timeout) {
        try {
            Thread.sleep(timeout);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    @SneakyThrows
    public static void t2() {
        CompletableFuture<Object> future = CompletableFuture.supplyAsync(() -> {

            return null;
        },executor);

        executor.execute(() -> {
            if(!future.isDone()) {
                future.complete("FinalResult");
            }
        });

        System.out.println("拿到结果: "+future.get(5,TimeUnit.SECONDS));
        threadSleep(2000);
        System.out.println("当前活跃线程数量: "+((ThreadPoolExecutor) executor).getActiveCount());
        System.in.read();
    }


    public static void main(String[] args) {
        t2();
    }

}
